package com.learn.security.web.async;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * 异步处理REST服务
 */
@RestController
public class AsyncController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    /**
     * 用Runnable实现异步请求
     */
    @GetMapping("/order")
    public Callable<String> order() throws InterruptedException {
        logger.info("主线程开始");
        Callable<String> result = () -> {
            logger.info("副线程开始");

            logger.info("副线程开始");
            return "success";
        };
        logger.info("主线程结束");
        return result;
    }

    /**
     * 用DeferredResult实现异步请求
     */
    @GetMapping("/order2")
    public DeferredResult<String> order2() throws InterruptedException {
        logger.info("主线程开始");

        String random = RandomStringUtils.randomNumeric(8);
        mockQueue.setPlaceHolder(random);

        DeferredResult<String> result = new DeferredResult<>();

        deferredResultHolder.getMap().put(random, result);

        logger.info("主线程返回");
        return result;
    }
}
